//根据二叉树创建字符串
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    string tree2str(TreeNode* root) 
    {
        //其实就是在前序遍历的基础上加上括号
        //需要考虑的匹配括号的问题
        // 1、左为空，右不为空 括号保留
        // 2、左为空，右为空 括号省略
        // 3、左不为空，右不为空 括号省略

        if(root == nullptr)
            return "";

        string str = to_string(root->val);

        if(root->left || root->right)
        {
            str += '(';
            str += tree2str(root->left);
            str += ')';
        }

        if(root->right)
        {
            str += '(';
            str += tree2str(root->right);
            str += ')';
        }

        
        return str;
    }
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    //用来判断在不在
    bool find(TreeNode* root, TreeNode* x)
    {
        if(root == nullptr) 
            return false;

        return root == x || find(root->left, x) || find(root->right, x);
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
    {
        if(root == nullptr)
            return nullptr;
        //当p 或 q 就是就是最近公共祖先时直接返回即可
        if(root == p)
            return p;
        if(root == q)
            return q;

        //创建四个bool类型变量用于判断p、q相较于目前root的位置。
        //若p和q相较于当前root的一左一右，那么root就是最近公共祖先。特殊情况，即
        bool pInLeft,pInRight,qInLeft,qInRight;

        pInLeft = find(root->left,p);
        pInRight = !pInLeft;

        qInLeft = find(root->left,q);
        qInRight = !qInLeft;

        if(pInLeft && qInLeft)
            return lowestCommonAncestor(root->left,p,q);
        else if(pInRight && qInRight)
            return lowestCommonAncestor(root->right,p,q);
        else
            return root;

    }
};

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    void InOrder(TreeNode* cur, TreeNode*& prev)
    {
        if(cur == nullptr)
            return;

        InOrder(cur->left, prev);

        cur->left = prev;
        if(prev)
        {
            prev->right = cur;
        }
        prev = cur;
        InOrder(cur->right, prev);

    }

    TreeNode* Convert(TreeNode* pRootOfTree) 
    {
        //更改后驱链接
        TreeNode* prev = nullptr;//表示前驱指针
        InOrder(pRootOfTree, prev);

        //更改前驱链接
        TreeNode* head = pRootOfTree;
        while(head && head->left)
        {
            head = head->left;
        }
        
        return head;
        
    }
};
